<template>
  <!-- 首页 -->
  <div class="dashboard-container">
    <div class="dashboard-text">
      <!-- 个人页面 -->
      <el-card>
        <el-button v-if="role != '已被禁用'" class="btn1" type="primary" icon="el-icon-edit" @click="openEditUI(id)">修改主页</el-button>
        <el-button v-else disabled class="btn1" type="primary" icon="el-icon-edit" @click="openEditUI(id)">修改主页</el-button>
        <div class="box">
          <div class="img">
            <img :src="userList.avatar" class="avatar2">
          </div>
          <div>
            <div>用户名: {{ userList.username }}</div>
            <div>
              密码：******
              <el-button v-if="role != '已被禁用'" class="btn3" type="warning" icon="el-icon-edit" @click="openEditPD(id)">忘记密码</el-button>
              <el-button v-else class="btn3" disabled type="primary" icon="el-icon-edit" @click="openEditPD(id)">忘记密码</el-button>
            </div>
            <div>电话: {{ userList.phone }}</div>
            <div>邮箱: {{ userList.email }}</div>
            <div>状态:
              <el-tag v-if="userList.status == 1">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
              <el-tag v-if="userList.status == 0" type="warning">被举报原因:{{ userList.cause }}</el-tag>
            </div>
            <div>
              权限: {{ role }}
              <el-button v-if="role == '已被禁用'" class="btn2" type="danger">联系管理员</el-button>
            </div>
            <div>
              金额: {{ userList.money }}元
              <el-button v-if="role != '已被禁用'" type="primary" @click="recharge">充值</el-button>
              <el-button v-else disabled type="primary">充值</el-button>
            </div>
          </div>
        </div>

      </el-card>
      <!--修改用户信息-->
      <el-dialog title="修改个人信息" :visible.sync="dialogFormVisible">
        <el-form ref="userFormRef" :model="userList" :rules="rules">
          <el-form-item prop="username" label="用户名" :label-width="formLabelWidth">
            <el-input v-model="userList.username" auto-complete="off" />
          </el-form-item>
          <!-- <el-form-item prop="password" label="登录密码" :label-width="formLabelWidth">
            <el-input v-model="userList.password" type="password" auto-complete="off" />
          </el-form-item> -->
          <el-form-item prop="phone" label="联系电话" :label-width="formLabelWidth">
            <el-input v-model="userList.phone" auto-complete="off" />
          </el-form-item>
          <el-form-item prop="email" label="电子邮件" :label-width="formLabelWidth">
            <el-input v-model="userList.email" auto-complete="off" />
          </el-form-item>
          <el-form-item prop="avatar" label="头像" :label-width="formLabelWidth">
            <!-- <el-input v-model="userList.avatar" auto-complete="off" /> -->
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8088/user"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="userList.avatar" :src="userList.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="nosave">取 消</el-button>
          <el-button type="primary" @click="saveUser">确 定</el-button>
        </div>
      </el-dialog>

      <!--修改密码-->
      <!-- <el-dialog title="修改密码" :visible.sync="dialogFormVisible2">
        <el-form ref="userFormRef2" :model="userList" :rules="rules">
          <el-form-item prop="password" label="新的登录密码" :label-width="formLabelWidth">
            <el-input v-model="userList.password" type="password" auto-complete="off" />
          </el-form-item>
          <el-form-item prop="password" label="再次输入密码" :label-width="formLabelWidth">
            <el-input v-model="userList.password" type="password" auto-complete="off" />
          </el-form-item>
          <el-form-item prop="phone" label="手机号码" :label-width="formLabelWidth">
            <el-input v-model="userList.phone" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="updatePd">确 定</el-button>
        </div>
      </el-dialog> -->
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import userApi from '@/api/userManage'

export default {
  // name: 'Dashboard',
  data() {
    var checkEmail = (rule, value, callback) => {
      var reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式错误'))
      }
      callback()
    }
    return {
      userList: {},
      role: '',
      dialogFormVisible: false,
      // dialogFormVisible2: false,
      formLabelWidth: '130px',
      rules: {
        username: [
          { required: true, message: '请输入用户名', tigger: 'blur' },
          { min: 3, max: 50, message: '长度在3到50个字符', tigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录初始密码', trigger: 'blur' },
          { min: 6, max: 100, message: '密码长度需要大于6个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮件', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'id'
    ])
  },
  created() {
    this.getUserById(this.id)
    // if (location.href.indexOf('#reloaded') === -1) {
    //   location.href = location.href + '#reloaded'
    //   location.reload()
    // }
  },
  destroyed() {
  },
  methods: {
    // 充值
    recharge() {
      this.userList.money += 5000
      userApi.updateMoney(this.userList).then(response => {
        this.$set(this.userList, 'money', this.userList.money)
        this.$message({
          message: '充值5000元成功!',
          type: 'success'
        })
      })
    },
    nosave() {
      this.dialogFormVisible = false
      this.timer = setTimeout(this.getUserById(this.id), 500)
    },
    saveUser() {
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          // 提交请求到后台
          userApi.saveUser(this.userList).then(response => {
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭对话框
            this.dialogFormVisible = false
            window.location.reload()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // updatePd() {
    //   this.$refs.userFormRef2.validate((valid) => {
    //     if (valid) {
    //       // 提交请求到后台
    //       userApi.saveUser(this.userList).then(response => {
    //         this.$message({
    //           message: response.message,
    //           type: 'success'
    //         })
    //         // 关闭对话框
    //         this.dialogFormVisible = false
    //         console.log(this.userList)
    //       })
    //     } else {
    //       console.log('error submit!!')
    //       return false
    //     }
    //   })
    // },
    openEditUI(id) {
      // 根据id查询用户数据
      userApi.getUserById(id).then(respose => {
        this.userList = respose.data
      })
      this.dialogFormVisible = true
    },
    // 根据用户id查询
    getUserById(id) {
      userApi.getUserById(id).then(respose => {
        this.userList = respose.data
        console.log(this.userList)
        // bolb转base64
        if (this.userList.flag === 1) {
          const image1 = new Image() // 新建一个img标签（还没嵌入DOM节点)
          // blob:http://localhost:8080/b878edea-e649-4f8d-b723-c3f25454141b
          image1.src = this.userList.avatar
          this.BlobToBase64(image1)
          delete image1.src
          console.log(this.userList.avatar)
        }
        if (respose.data.roleIdList[0] === 1) {
          this.role = '超级管理员'
        } else if (respose.data.roleIdList[0] === 2) {
          this.role = '审查员'
        } else if (respose.data.roleIdList[0] === 3) {
          this.role = '学生'
        } else {
          this.role = '已被禁用'
        }
      })
    },
    // 图片
    BlobToBase64(image) {
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        this.userList.avatar = canvas.toDataURL() // 图片的base64地址
        console.log(this.userList.avatar)
        this.$set(this.userList, 'avatar', this.userList.avatar)
        userApi.updateUser(this.userList).then(response => {
        })
        console.log(this.userList.avatar)
      }
    },
    handleAvatarSuccess(res, file) {
      // bolb转base64
      const image = new Image() // 新建一个img标签（还没嵌入DOM节点)
      image.src = URL.createObjectURL(file.raw)
      this.BlobToBase64(image)
      // this.userList.avatar = URL.createObjectURL(file.raw)
      // console.log(this.userList.avatar)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
  .dashboard-container {
    margin: 30px;
  }
  .dashboard-text {
    font-size: 30px;
    line-height: 46px;
  }
  .avatar2{
    width: 300px;
    height: 100%;
    margin-right: 30px;
    border-radius: 10px;
    box-shadow:rgba(0,0,0,0.2) 0 1px 5px 0px;
  }
  .el-card{
      position: relative;
  }
  .btn1{
      position: absolute;
      right: 0;
      top: 0;
  }
  .btn2{
    margin-left: 50px;
  }
  .box{
    display: flex;
  }
  .hide{
    display: none;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
